//
//  KABModel.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABModel.h"
#import "GlobalHeader.h"
#import <JPUSHService.h>
#import <RongIMKit/RongIMKit.h>

static NSString *const kKabModelFilePath = @"kKabModelFilePath";

//static NSString *const kCosplayListWholeFileName = @"kCosplayListWholeFileName";
//static NSString *const kCosplayListRecommendFileName = @"kCosplayListRecommendFileName";
//static NSString *const kCosplayListFollowFileName = @"kCosplayListFollowFileName";
//static NSString *const kCosplayCelebrityFileName = @"kCosplayCelebrityFileName";
//
//static NSString *const kExhibitionListFileName = @"kExhibitionListFileName";
//
//static NSString *const kMallBannerListFileName = @"kMallBannerListFileName";
//static NSString *const kMallProductListFileName = @"kMallProductListFileName";
//static NSString *const kMallProductTypeFileName = @"kMallProductTypeFileName";

@implementation KABModel
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }

+ (instancetype)sharedInstance {
    static KABModel *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
//- (instancetype)init {
//    self = [super init];
//    if (self) {
//        [self getFromDisk];
//    }
//    return self;
//}
- (BOOL)saveToDisk {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *modelPath = [document stringByAppendingPathComponent:kKabModelFilePath];
    return [NSKeyedArchiver archiveRootObject:self toFile:modelPath];
    
//    // Cosplay
//    NSString *cosWholePath = [document stringByAppendingPathComponent:kCosplayListWholeFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.cosplayListWhole toFile:cosWholePath]) {
//        NSLog(@"归档 %@ 成功!", kCosplayListWholeFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kCosplayListWholeFileName);
//    }
//    NSString *cosRecommendPath = [document stringByAppendingPathComponent:kCosplayListRecommendFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.cosplayListRecommend toFile:cosRecommendPath]) {
//        NSLog(@"归档 %@ 成功!", kCosplayListRecommendFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kCosplayListRecommendFileName);
//    }
//    NSString *cosFollowPath = [document stringByAppendingPathComponent:kCosplayListFollowFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.cosplayListFollow toFile:cosFollowPath]) {
//        NSLog(@"归档 %@ 成功!", kCosplayListFollowFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kCosplayListFollowFileName);
//    }
//    NSString *cosCelebrityPath = [document stringByAppendingPathComponent:kCosplayCelebrityFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.cosplayCelebrity toFile:cosCelebrityPath]) {
//        NSLog(@"归档 %@ 成功!", kCosplayCelebrityFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kCosplayCelebrityFileName);
//    }
//    
//    // 展会
//    NSString *exhibitionListPath = [document stringByAppendingPathComponent:kExhibitionListFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.exhibitionList toFile:exhibitionListPath]) {
//        NSLog(@"归档 %@ 成功!", kExhibitionListFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kExhibitionListFileName);
//    }
//    
//    // 商城
//    NSString *mallBannerListPath = [document stringByAppendingPathComponent:kMallBannerListFileName];
//    if ([NSKeyedArchiver archiveRootObject:self.mallBannerList toFile:mallBannerListPath]) {
//        NSLog(@"归档 %@ 成功!", kMallBannerListFileName);
//    } else {
//        NSLog(@"归档 %@ 失败!", kMallBannerListFileName);
//    }
//    
//    // 个人中心
}
- (BOOL)getFromDisk {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *modelPath = [document stringByAppendingPathComponent:kKabModelFilePath];
    NSLog(@"保存的沙盒路径(%@)", modelPath);
    KABModel *temp = [NSKeyedUnarchiver unarchiveObjectWithFile:modelPath];
    if (!temp) {
        return NO;
    }
    
    self.userInfo = temp.userInfo;
    self.receiverList = temp.receiverList;
    self.mineNewMsg = temp.mineNewMsg;
    
    self.cosplayListWhole = temp.cosplayListWhole;
    self.cosplayListRecommend = temp.cosplayListRecommend;
    self.cosplayListFollow = temp.cosplayListFollow;
    self.cosplayCelebrity = temp.cosplayCelebrity;
    
    self.exhibitionList = temp.exhibitionList;
    
    self.mallHomepage = temp.mallHomepage;
    self.mallBannerList = temp.mallBannerList;
    self.mallProductList = temp.mallProductList;
    self.mallProductType = temp.mallProductType;
    
    return YES;
    
//    // Cosplay
//    NSString *cosWholePath = [document stringByAppendingPathComponent:kCosplayListWholeFileName];
//    self.cosplayListWhole = [NSKeyedUnarchiver unarchiveObjectWithFile:cosWholePath];
//
//    NSString *cosRecommendPath = [document stringByAppendingPathComponent:kCosplayListRecommendFileName];
//    self.cosplayListRecommend = [NSKeyedUnarchiver unarchiveObjectWithFile:cosRecommendPath];
//    
//    NSString *cosFollowPath = [document stringByAppendingPathComponent:kCosplayListFollowFileName];
//    self.cosplayListFollow = [NSKeyedUnarchiver unarchiveObjectWithFile:cosFollowPath];
//    
//    NSString *cosCelebrityPath = [document stringByAppendingPathComponent:kCosplayCelebrityFileName];
//    self.cosplayCelebrity = [NSKeyedUnarchiver unarchiveObjectWithFile:cosCelebrityPath];
//    
//    // 商城
//    NSString *mallBannerListPath = [document stringByAppendingPathComponent:kMallBannerListFileName];
//    self.mallBannerList =  [NSKeyedUnarchiver unarchiveObjectWithFile:mallBannerListPath];
}
@end


@implementation KABModel (LoginRelative)
- (BOOL)isLogin {
    return (self.userInfo != nil);
}

- (KABLoginModel *)loginModelWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.userInfo = [KABLoginModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
        // 绑定极光推送Alias
        NSString *aliasStr = [NSString stringWithFormat:@"%zd", self.userInfo.uid];
        NSLog(@"极光推送的别名是%@", aliasStr);
        [JPUSHService setTags:nil aliasInbackground:aliasStr];
        // 融云IM上线
        [self rongCloudOnLine];
    }
    return self.userInfo;
}
- (void)updateTokenByModifyPwd:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.userInfo.access_token = dic[KABGlobalJsonKeyResult][@"access_token"];
    }
}
- (void)saveUserInfoWithPwd:(NSString *)pwd {
    [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.account forKey:KABGlobalUserDefaultsAccount];
    [[NSUserDefaults standardUserDefaults] setObject:pwd forKey:KABGlobalUserDefaultsPwd];
//    [[NSUserDefaults standardUserDefaults] setInteger:self.userInfo.uid forKey:KABGlobalUserDefaultsUid];
//    [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.access_token forKey:KABGlobalUserDefaultsAccessToken];
    
    // 登录成功，缓存一下数据，主要是保存Token
    [self saveToDisk];
}
- (void)saveWxAccessToken {
    if (self.userInfo.login_method == 1) {
        [[NSUserDefaults standardUserDefaults] setObject:self.userInfo.access_token forKey:KABGlobalUserDefaultsWXAccessToken];
    }
    
    // 登录成功，缓存一下数据，主要是保存Token
    [self saveToDisk];
}
- (void)rongCloudOnLine {
    if (!self.userInfo.rongcloud_token.length) {
        return;
    }
    // 融云断开连接
    [[RCIM sharedRCIM] logout];
    // 融云开始连接
    [[RCIM sharedRCIM] connectWithToken:self.userInfo.rongcloud_token success:^(NSString *userId) {
        NSLog(@"融云连接成功，userId = %@", userId);
        [self refreshRongCloudOwnerInfo];
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        NSLog(@"token错误");
    }];
}
- (void)refreshRongCloudOwnerInfo {
    RCUserInfo *rcUserInfo = [[RCUserInfo alloc] initWithUserId:self.userInfo.uidStr name:self.userInfo.nick_name portrait:self.userInfo.headimg_url];
    [RCIM sharedRCIM].currentUserInfo = rcUserInfo;
}
- (void)logout {
    // 极光推送，取消用用户的uid绑定为别名(退出之后就不用收到推送)
    [JPUSHService setTags:nil aliasInbackground:@""];
    // 融云断开连接
    [[RCIM sharedRCIM] logout];
    
    // 清理自动登录的标记
    if (self.userInfo.login_method == 0) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KABGlobalUserDefaultsPwd];
    } else if (self.userInfo.login_method == 1) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KABGlobalUserDefaultsWXAccessToken];
    }
    // 清空内存的个人数据
    self.userInfo = nil;
    self.receiverList = nil;
    
    // 清空磁盘的个人数据
    [self saveToDisk];
}
- (void)updateNickName:(NSString *)nickName
                   sex:(NSInteger)sex
              province:(NSString *)province
                  city:(NSString *)city
                  sign:(NSString *)sign {
    if (nickName) {
        self.userInfo.nick_name = nickName;
    }
    if (sex != -1) {
        self.userInfo.sex = sex;
    }
    if (province) {
        self.userInfo.province = province;
    }
    if (city) {
        self.userInfo.city = city;
    }
    if (sign) {
        self.userInfo.sign = sign;
    }
    
    // 更新融云的信息
    [self refreshRongCloudOwnerInfo];
}

- (KABLoginModel *)updateLoginInfoWithMineInfo:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        KABMineInfo *temp = [KABMineInfo yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
        [self.userInfo updateInfoWithMineInfo:temp];
        // 更新融云的信息
        [self refreshRongCloudOwnerInfo];
    }
    
    return self.userInfo;
}

- (KABReceiverInfoList *)receiverListWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.receiverList = [KABReceiverInfoList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    }
    return self.receiverList;
}
- (KABMineNewMsg *)mineNewMsgWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.mineNewMsg = [KABMineNewMsg yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    }
    
    // 更新未读消息界面(小红点)
    [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiMsgRedDotShow object:nil userInfo:nil];
    
    return self.mineNewMsg;
}
@end


@implementation KABModel (CosplayRelative)
- (KABCosplayModel *)cosplayListWholeWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.cosplayListWhole;
    }
    
    KABCosplayModel *temp = [KABCosplayModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.cosplayListWhole;
    }
    
    if (addMore && self.cosplayListWhole) {
        [self.cosplayListWhole addMoreWithData:temp];
    } else {
        self.cosplayListWhole = temp;
    }
    return self.cosplayListWhole;
}

- (KABCosplayModel *)cosplayListRecommendWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.cosplayListRecommend;
    }
    
    KABCosplayModel *temp = [KABCosplayModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.cosplayListRecommend;
    }
    
    if (addMore && self.cosplayListRecommend) {
        [self.cosplayListRecommend addMoreWithData:temp];
    } else {
        self.cosplayListRecommend = temp;
    }
    return self.cosplayListRecommend;
}

- (KABCosplayModel *)cosplayListFollowWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.cosplayListFollow;
    }
    
    KABCosplayModel *temp = [KABCosplayModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.cosplayListFollow;
    }
    
    if (addMore && self.cosplayListFollow) {
        [self.cosplayListFollow addMoreWithData:temp];
    } else {
        self.cosplayListFollow = temp;
    }
    return self.cosplayListFollow;
}

- (KABCosplayCelebrity *)cosplayCelebrityWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.cosplayCelebrity;
    }
    
    KABCosplayCelebrity *temp = [KABCosplayCelebrity yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.cosplayCelebrity;
    }
    
    if (addMore && self.cosplayCelebrity) {
        [self.cosplayCelebrity addMoreWithData:temp];
    } else {
        self.cosplayCelebrity = temp;
    }
    return self.cosplayCelebrity;
}

@end



@implementation KABModel (ExhibitionRelative)
- (KABExhibitionModel *)exhibitionListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.exhibitionList;
    }
    
    KABExhibitionModel *temp = [KABExhibitionModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.exhibitionList;
    }
    
    if (addMore && self.exhibitionList) {
        [self.exhibitionList addMoreWithData:temp];
    } else {
        self.exhibitionList = temp;
    }
    return self.exhibitionList;
}

@end



@implementation KABModel (MallRelative)
- (KABMallHomepage *)mallHomepageWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.mallHomepage = [KABMallHomepage yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    }
    return self.mallHomepage;
}
- (KABMallBannerList *)mallBannerListWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.mallBannerList = [KABMallBannerList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    }
    return self.mallBannerList;
}

- (KABMallProductList *)mallProductListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)addMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.mallProductList;
    }
    
    KABMallProductList *temp = [KABMallProductList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.mallProductList;
    }
    
    if (addMore && self.mallProductList) {
        [self.mallProductList addMoreWithData:temp];
    } else {
        self.mallProductList = temp;
    }
    return self.mallProductList;
}
- (KABMallProductType *)mallProductTypeWithDictionary:(NSDictionary *)dic {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] == 200) {
        self.mallProductType = [KABMallProductType yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    }
    return self.mallProductType;
}
@end

